package org.gd136.ce.script.impl;

import org.gd136.ce.script.Script;
import org.gd136.ce.script.ScriptStage;

public class IfScript extends Script {

	private static final String TAG = "#if ";

	static IfScript lastIfScript;

	ElseIfScript nextIfScript;
	IfEndScript ifEndScript;

	String checkParam;

	@Override
	public Script readScript(String scriptLine) {
		IfScript is = null;
		if (scriptLine.startsWith(TAG)) {
			is = new IfScript();
			is.checkParam = scriptLine.substring(TAG.length());
			if (lastIfScript != null) {
				throw new IllegalArgumentException("if 没有ifEnd结尾! file["
						+ fileName + "] line[" + lineNum + "]");
			}
			lastIfScript = is;
			is.addToPoolAndLinkFrontScript();
		}
		return is;
	}

	@Override
	public void execute(ScriptStage stage) {
		if (SM.getCurrentScript() != this) {
			throw new IllegalArgumentException("If is not currentScript!");
		}
		SM.stack.remove(SM.stack.size() - 1);
		SM.stack.add(ifEndScript);
		SM.stack.add(this);
		if (!stage.ifCheck(checkParam)) {
			SM.stack.remove(SM.stack.size() - 1);
			if (nextIfScript != null) {
				SM.stack.add(nextIfScript);
			}
		}
	}

}
